package com.weir.quarkus.base.system.handler;

import com.weir.quarkus.base.system.entity.BaseEntity;
import com.weir.quarkus.base.system.entity.SysUser;

import io.vertx.core.json.JsonObject;

import org.eclipse.microprofile.jwt.Claims;
import org.eclipse.microprofile.jwt.JsonWebToken;

import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.spi.CDI;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;

@RequestScoped
public class BaseEntityListener {

	public BaseEntityListener() {}

	private SysUser getUser(String userJson) {
		return new JsonObject(new JsonObject(userJson).getValue("user").toString()).mapTo(SysUser.class);
	}

	@PrePersist
    public void prePersist(Object target) {
		JsonWebToken context = CDI.current().select(JsonWebToken.class).get();
		Object claim = context.getClaim(Claims.preferred_username.name());
		SysUser user = getUser(claim.toString());
		if (target instanceof BaseEntity) {
			BaseEntity baseEntity = (BaseEntity) target;
			baseEntity.creator = user.id;
		}
	}
	@PreUpdate
    public void preUpdate(Object target) {
		JsonWebToken context = CDI.current().select(JsonWebToken.class).get();
		Object claim = context.getClaim(Claims.preferred_username.name());
		SysUser user = getUser(claim.toString());
		if (target instanceof BaseEntity) {
			BaseEntity baseEntity = (BaseEntity) target;
			baseEntity.modifier = user.id;
		}
	}
}
